#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTextBlock>
#include <QClipboard>
#include <QSpacerItem>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    BuildUI();
    InitConnect();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actFile_New_triggered()
{
    QString cur = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getSaveFileName(this, "新建文件", cur, "文本文件 (*.txt);; 所有文件(*.*)");

    if(fileName.isEmpty())
    {
        // QMessageBox::warning(this, "错误", "无法创建文件");
        qDebug("文件名为空，取消或者关闭了窗口");
        return;
    }
    else
    {
        // if(QFile::exists(fileName))
        // {
        //     QMessageBox::StandardButton reply;
        //     reply = QMessageBox::question(this, "确认覆盖", "文件已存在，是否覆盖？",  QMessageBox::Yes | QMessageBox::No);
        //     if(reply == QMessageBox::No)
        //         return;
        // }

        QFile file(fileName);
        if(file.open(QIODevice::ReadWrite | QIODevice::Text))
        {
            QMessageBox::information(this, "提示", "创建文件成功");
            m_isFileOpen = true;
            m_file.reset(new QFile(fileName));
            ui->actFile_Save->setEnabled(true);
        }
        else
        {
            QMessageBox::warning(this, "错误", "文件创建失败");
            return;
        }
    }
}

void MainWindow::on_actFile_Open_triggered()
{
    ui->plainTextEdit->clear();
    QString cur = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getOpenFileName(this, "打开文件",  cur, "文本文件 (*.txt);; 所有文件(*.*)");

    if(fileName.isEmpty())
    {
        // QMessageBox::warning(this, "错误", "无法打开文件");
        qDebug("文件名为空，取消或者关闭了窗口");
        return;
    }
    else
    {
        QFile file(fileName);
        if(file.open(QIODevice::ReadWrite | QIODevice::Text))
        {
            QTextStream in(&file);
            while(!in.atEnd())
            {
                QString line = in.readLine();
                ui->plainTextEdit->appendPlainText(line);
            }
        }
        else
        {
            QMessageBox::warning(this, "错误", "文件打开失败");
            return;
        }

        m_isFileOpen = true;
        m_file.reset(new QFile(fileName));
        ui->actFile_Save->setEnabled(true);
        QMessageBox::information(this, "提示", "打开文件成功");
    }
}

void MainWindow::on_actFile_Save_triggered()
{
    if(m_isFileOpen && m_file != nullptr)
    {
        m_isFileOpen = false;
    }
    else
    {
        QString cur = QCoreApplication::applicationDirPath();
        QString fileName = QFileDialog::getSaveFileName(this, "新建文件", cur, "文本文件 (*.txt);; 所有文件(*.*)");

        if(fileName.isEmpty())
        {
            // QMessageBox::warning(this, "错误", "无法创建文件");
            qDebug("文件名为空，取消或者关闭了窗口");
            return;
        }
        m_file.reset(new QFile(fileName));
    }
    if(m_file.get()->open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(m_file.get());
        //int blockCount = ui->plainTextEdit->document()->blockCount();
        QTextDocument *doc = ui->plainTextEdit->document();
        for(QTextBlock it = doc->begin(); it != doc->end(); it = it.next())
        {
            out << it.text() << "\n";
        }
    }
    else
    {
        QMessageBox::warning(this, "错误", "文件保存失败");
        return;
    }
    ui->actFile_Save->setEnabled(false);
    // QMessageBox::information(this, "提示", "保存文件成功");
}

void MainWindow::on_actEdit_Copy_triggered()
{
    // QClipboard* clipboard = QApplication::clipboard();
    // clipboard->setText(ui->plainTextEdit->textCursor().selectedText());
    ui->plainTextEdit->copy();
    ui->actEdit_Paste->setEnabled(true);
    ui->actEdit_Copy->setEnabled(false);
    ui->actEdit_Cut->setEnabled(false);
}

void MainWindow::HandelTextChanged()
{
    ui->actFile_Save->setEnabled(true);
    ui->actEdit_Undo->setEnabled(true);
    ui->actEdit_Redo->setEnabled(true);
}

void MainWindow::HandelSelectionChanged()
{
    ui->actEdit_Copy->setEnabled(true);
    ui->actEdit_Cut->setEnabled(true);
    ui->actFont_Bold->setEnabled(true);
    ui->actFont_Italic->setEnabled(true);
}

void MainWindow::InitConnect()
{
    connect(ui->plainTextEdit, &QPlainTextEdit::textChanged, this, &MainWindow::HandelTextChanged);
    connect(ui->plainTextEdit, &QPlainTextEdit::selectionChanged, this, &MainWindow::HandelSelectionChanged);
    connect(this->spinFontSize, &QSpinBox::valueChanged, this, &MainWindow::HandelFontSize);
    connect(this->comboFontName, &QFontComboBox::currentFontChanged, this, &MainWindow::HandelFont);
    connect(this->comboFontName, &QFontComboBox::currentTextChanged, this, &MainWindow::HandelFontName);
}

void MainWindow::BuildUI()
{
    // QSpinBox* spinBox = new QSpinBox(this);
    // spinBox->setMinimumWidth(100);
    // spinBox->setValue(ui->plainTextEdit->font().pointSize());
    // ui->toolBar->addWidget(spinBox);


    spinFontSize =  new QSpinBox(this);
    spinFontSize->setMinimumWidth(50);
    spinFontSize->setValue(ui->plainTextEdit->font().pointSize());
    ui->toolBar->addWidget(spinFontSize);

    comboFontName = new QFontComboBox(this);
    comboFontName->setMinimumWidth(100);
    comboFontName->setCurrentFont(ui->plainTextEdit->font());
    ui->toolBar->addWidget(comboFontName);

    ui->toolBar->addSeparator();

    actionGroup = new QActionGroup(this);
    actionGroup->addAction(ui->actLang_CN);
    actionGroup->addAction(ui->actLang_EN);
    actionGroup->setExclusive(true);
    ui->actLang_CN->setChecked(true);

    ui->toolBar->addAction(ui->actClose);

    labFile= new QLabel("文件名：", this);
    labFile->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    labFile->setMinimumWidth(200);
    ui->statusbar->addWidget(labFile);

    progressBar1 = new QProgressBar(this);
    progressBar1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    progressBar1->setFormat("%p%");
    progressBar1->setTextVisible(true);
    progressBar1->setValue(spinFontSize->value());
    progressBar1->setMinimumWidth(200);
    //progressBar1->setMaximumWidth(300);
    ui->statusbar->addWidget(progressBar1);

    //QSpacerItem *spacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QWidget *spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    spacer->setMinimumWidth(200);
    ui->statusbar->addWidget(spacer);

    // QLabel *spacer = new QLabel();
    // spacer->setFixedWidth(200); // 设置固定宽度
    //  ui->statusbar->addWidget(spacer);

    labInfo = new QLabel("字体名称：", this);
    labInfo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    labInfo->setMinimumWidth(300);
    ui->statusbar->addPermanentWidget(labInfo);
}


void MainWindow::on_actEdit_Cut_triggered()
{
    // QClipboard* clipboard = QApplication::clipboard();
    // clipboard->setText(ui->plainTextEdit->textCursor().selectedText());
    ui->plainTextEdit->cut();
    ui->actEdit_Paste->setEnabled(true);
    ui->actEdit_Copy->setEnabled(false);
    ui->actEdit_Cut->setEnabled(false);
}

void MainWindow::on_actEdit_Paste_triggered()
{
    ui->plainTextEdit->paste();
    ui->actEdit_Paste->setEnabled(false);
    ui->actEdit_Copy->setEnabled(false);
    ui->actEdit_Cut->setEnabled(false);
}

void MainWindow::on_actEdit_Clear_triggered()
{
    ui->plainTextEdit->clear();
}

void MainWindow::on_actEdit_Undo_triggered()
{
    ui->plainTextEdit->undo();
    //ui->actEdit_Undo->setEnabled(false);
}

void MainWindow::on_actEdit_Redo_triggered()
{
    ui->plainTextEdit->redo();
    //ui->actEdit_Redo->setEnabled(false);
}

void MainWindow::on_actEdit_SelectAll_triggered()
{
    ui->plainTextEdit->selectAll();
    ui->actEdit_SelectAll->setEnabled(false);
}


void MainWindow::on_actFont_Bold_triggered(bool checked)
{
    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    if(checked)
        fmt.setFontWeight(QFont::Bold);
    else
        fmt.setFontWeight(QFont::Normal);
    ui->plainTextEdit->mergeCurrentCharFormat(fmt);

    //ui->actFont_Bold->setEnabled(false);
}

void MainWindow::on_actFont_UnderLine_triggered(bool checked)
{
    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    fmt.setFontUnderline(checked);
    ui->plainTextEdit->mergeCurrentCharFormat(fmt);
}

void MainWindow::on_actFont_Italic_triggered(bool checked)
{
    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    fmt.setFontItalic(checked);
    ui->plainTextEdit->mergeCurrentCharFormat(fmt);
}

void MainWindow::on_actSys_ToggleText_triggered(bool checked)
{
    if(checked)
    {
        ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    }
    else
    {
        ui->toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
    }
}

void MainWindow::HandelFontSize(int size)
{
    // QFont font = ui->plainTextEdit->font();
    // font.setPixelSize(size);
    // ui->plainTextEdit->setFont(font);
    // this->progressBar1->setValue(size);

    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    fmt.setFontPointSize(size); //设置字体大小
    ui->plainTextEdit->mergeCurrentCharFormat(fmt);
    progressBar1->setValue(size);
}

void MainWindow::HandelFont(const QFont& font)
{
    // ui->plainTextEdit->setFont(font);
    // this->labInfo->setText(font);
    labInfo->setText("字体名称："+font.family());  //状态栏上显示
    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    fmt.setFont(font);
    ui->plainTextEdit->mergeCurrentCharFormat(fmt);

}

void MainWindow::HandelFontName(const QString &str)
{
    //this->labInfo->setText("字体名称：" + str);
}


void MainWindow::on_plainTextEdit_selectionChanged()
{
    QTextCharFormat fmt=ui->plainTextEdit->currentCharFormat();
    ui->actFont_Bold->setChecked(fmt.font().bold());    //粗体
    ui->actFont_Italic->setChecked(fmt.fontItalic());   //斜体
    ui->actFont_UnderLine->setChecked(fmt.fontUnderline()); //下划线
}

